import React from 'react'

import FileIcon from '@/resource/file_icon.png'
import CloseCircle from '@/resource/close_circle.png'
import Plus from '@/resource/plus.png'
import type { BaseUploadInterface } from './BaseUpload'
import BaseUpload from './BaseUpload'

import styles from './index.module.less'

/**
 * Form 表单上传样式组件
 * label          string     标题文本
 * uploadText     string     上传按钮文案
 * tips           string     提示文案
 * value          { url, name? }[]      上传图片数据
 * required       bool       是否显示必填icon
 */
interface fileUploadInterface extends BaseUploadInterface {
    label: string
    uploadText?: string
    tips?: string
    required?: boolean
}

function FileUpload({ label, uploadText, tips = '', value = [], onChange, required, style = {}, ...restProps }: fileUploadInterface) {
    /** 删除事件回调 */
    function fnRemove(idx: number) {
        const newVal = [...value]
        newVal.splice(idx, 1)
        onChange?.(newVal)
    }

    return (
        <div className={styles['file-upload-container']} style={style}>
            <div className={styles['file-title-wrapper']}>
                <span className={required ? 'required-asterisk' : ''}>{label}</span>
                <BaseUpload value={value} onChange={onChange} {...restProps}>
                    {uploadText || (
                        <span className="plus-wrapper">
                            <img className="plus-icon" src={Plus} alt="" />
                            上传文件
                        </span>
                    )}
                </BaseUpload>
            </div>
            {tips && <div className="tips">{tips}</div>}
            {value &&
                value?.map((item: any, idx) => {
                    return (
                        <div className="file-item-wrap" key={`${item.url}_${idx}`}>
                            <div className="file-item ellipsis" key={item.url}>
                                <img className="file-icon" src={FileIcon} alt="" />
                                <span className="ellipsis">{item.name}</span>
                            </div>
                            <img onClick={() => fnRemove(idx)} className="file-close-circle" src={CloseCircle} alt="" />
                        </div>
                    )
                })}
        </div>
    )
}

export default FileUpload
